package com.changgou.pay.controller;


import com.alibaba.fastjson.JSON;
import com.changgou.pay.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import com.sun.org.apache.xerces.internal.util.HTTPInputSource;
import entity.IdWorker;
import entity.Result;
import entity.StatusCode;
import jdk.nashorn.internal.objects.annotations.Where;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixin/pay")
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private IdWorker idWorker;


    /**
     * 创建二维码
     * @param parameter  :金额,二维码地址,队列,交换机,rontingkey路由
     * @return
     */
    @RequestMapping(value = "/createNative")
    public Result<Map<String,String>> createNative(@RequestParam(required = false) Map<String,String> parameter){

        //二维码需要支付的金额
        //String money ="1";  //1分钱
        //二维码需要的随机订单号
       // long out_trade_no = idWorker.nextId();

        //可以把用户名传过去
        Map<String,String> map = weixinPayService.createNative(parameter);

        return  new Result<Map<String,String>>(true, StatusCode.OK,"二维码生成成功",map);

    }


    /**
     * 用来查看订单的支付状态情况
     *
     * @param out_trade_no
     * @return
     */
    @RequestMapping("/status/query")
    public Result queryStatus(String out_trade_no){
        Map<String,String> map = weixinPayService.queryStatus(out_trade_no);
        return  new Result<Map<String,String>>(true, StatusCode.OK,"查询支付状态成功",map);

    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;



    /**
     *
     * 用来接收支付信息的回调,然后在做业务处理
     * @param request
     * @return
     */
    @RequestMapping("/notify/url")
    public  String notifyuurl(HttpServletRequest request) {

        System.out.println("收到了微信的信息");

        ServletInputStream inputStream = null;

        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            //1.获取流信息
             inputStream = request.getInputStream();

            //2.转换成字节数组
             byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int lent =0;
            //把inputStream流放到byte里面在通过字节转换给byteArrayOutputStream
            while ((lent = inputStream.read(buffer))!= -1){
                byteArrayOutputStream.write(buffer,0 ,lent );
            }


            //3.转换成字符串(xml)
            byte[] bytes = byteArrayOutputStream.toByteArray();
            String resultString = new String(bytes, "UTF-8");
            //String resultString = new String(bytes);

            System.out.println(resultString);

            //4.转换成map,做业务处理
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(resultString);


            String attach = stringStringMap.get("attach"); //json格式的字符串(包含:发送过来的队列,路由key和交换机,附件)

            Map<String,String> attachMap = JSON.parseObject(attach, Map.class);

            //用来获得数据
            String exchange = attachMap.get("exchange");  //获得交换机的数据
            String routingkey = attachMap.get("routingkey"); //获得路由key的数据


            //把消息内容全部放到mq 里面
            //JSON.toJSONString(stringStringMap) :转为object格式
            //微信支付系统传递的数据(是一开始用户传递给微信的):主要用来判断是普通订单还是秒杀订单
            rabbitTemplate.convertAndSend(exchange, routingkey, JSON.toJSONString(stringStringMap));


            //5.返回给微信的字符串xml
            Map<String,String> XMLmap = new HashMap<>();

            XMLmap.put("return_code", "SUCCESS");  //必须的参数两个
            XMLmap.put("return_msg", "OK");

            String s = WXPayUtil.mapToXml(XMLmap);  //map转换成xml


            return  s;
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }finally {
            if (inputStream !=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (byteArrayOutputStream !=null){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
